//定义全局变量
var adminGrid;//表格
var dhxWins,addAdminWin,authorityWin; //窗口
var searchType=[['', '-- 请选择 --'],['1', '支付宝账号'], ['2', '用户名'],['3', '手机号']];
var oneAdminInfo; //一条管理员
var editStatus; //管理员状态
var dhxWinPwd, w1, pwdForm;
//页面布局
var pageObj = {type:"0100",height:[50,,45],paging:true,size:15}
var layoutContainer = create_layout(pageObj);
//初始化操作
$(function(){
    initGrid();
});
//初始化表格
function initGrid(){
    //获取表格对象
    adminGrid = layoutContainer.grid[0];
    //定义表格表头
    var columnsInfo=[
        {header:'id',id:'id',width:'*',hidden:true},
        {header:'支付宝USERID',id:'alipay_id',width:'*'},
        {header:'支付宝账号',id:'alipay_account',width:150 },
        {header:'手机号',id:'phone',width:150 },
        {header:'idcard_no',id:'idcard_no',width:150,hidden:true},
        {header:'id_kind',id:'id_kind',width:150,hidden:true},
        {header:'用户名',id:'real_name',width:150},
        {header:'备注',id:'remark',width:150,hidden:true},
        {header:'状态',id:'status',width:150,type:'combo'},
        {header:'管理员类型',id:'user_type',width:150,type:'combo'},
        {header:'登入时间',id:'last_login_num',width:130  ,hidden:true},
        {header:'登入次数',id:'login_num',width:130  ,hidden:true},
        {header:'创建时间',id:'gmt_create',width:'*'},
        {header:'修改时间 ',id:'gmt_modify',width:130  ,hidden:true },
        {header:'操作人员',id:'operator',width:130 },
    ];
    //创建表格
    dmjplugs.grid.createGrid({ sm:'ch',  skin:'dhx_skyblue', srcc:true,  columns:columnsInfo },adminGrid);
    adminGrid.setTotal(0);
    adminGrid.getColumnCombo(adminGrid.getColIndexById('status')).addOption(statusComboData);
    adminGrid.getColumnCombo(adminGrid.getColIndexById('user_type')).addOption(roleTypeComboData);
    adminGrid.enableEditEvents(false,false,false);
    //注册分页事件
    adminGrid.attachEvent("loadPagingData", function(first, limit){
        findPageGrid(first, limit);
    });
    //注册行点击事件
    adminGrid.attachEvent("onRowSelect",doOnRowSelected);
    adminGrid.attachEvent("onRowDblClicked",function () {
        doEdit('edit');
    });
    //隐藏掉复选框
    adminGrid.setColumnHidden(0,true);

    //获取表格数据
    findPageGrid();

}
//根据选择条件,获取表格数据	
function findPageGrid(first,limit){
    //初始化表格为空表
    if (!limit) {
        first = 0;
        limit = adminGrid.getPageRowLimit();
        adminGrid.clearAll();
        adminGrid.setTotal(0);
    }
    //分页组件数据
    var postData="pageNo="+parseInt(first/limit+1)+"&pageSize="+limit+"&pageCount="+adminGrid.getPageTotal()+"&hosType=2" ;
    //查询条件
    if (typeof (search_Form) == 'object') {
        var formData = search_Form.getFormData();//获取查询表单数据
        var searchKey = search_Form.getInput("searchKey").value;
        var searchType=formData.searchType;
        if(searchKey&&searchKey.length>0) postData+=(searchType==1?"&alipayAccount=":searchType==2?"&realName=":searchType==3?"&phone=":"&bb=")+searchKey;
    }
    $.ajax({
        url: basePath+'managerAlipayUser/pagefindAlipayUserGrid',
        type: 'post',
        dataType: 'json', //返回的数据类型
        data:encodeURI(postData),
        success: function (data) {
            if(data&&data.rowCount>0){
                adminGrid.parse(data.gridr, "json");
                adminGrid.setTotal(data.rowCount);
                adminGrid.uncheckAll();
            }
        }
    });
}
//------------------------------------------------顶部操作区----------------------------------------------------------------------
// 顶部查询按钮	注册点击事件
function doOnButtFormInit() {
    if (typeof (butt_Form) == 'object') {
        butt_Form.attachEvent("onButtonClick",function(name,command) {
            if (command == 'add')//新增
                doAdd('add');
            else if (command == 'edit')//编辑
                doEdit('edit');
            else if (command == 'freeze')//冻结账号
                doFreeze();
            else if (command == 'refresh')//刷新
                doRefresh();
            else if (command == 'delete')//删除用户
                doDelete();
            else if (command == 'authority')//数据授权
                doAuthority();
        });
    }
}
//顶部查询框初始化	
function doOnSearchFormInit(){
    if (typeof(search_Form) == "object"){
        moduleSearchInit();
        search_Form.attachEvent("onButtonClick", function(name, command) {
            if (command == 'search')
                doRefresh();
            else if(command == 'reset')
                doReset();
        });
        var searchType_combo=search_Form.getCombo('searchType');
        searchType_combo.addOption(searchType);
        searchType_combo.setComboValue('1');
        searchType_combo.readonly(true);
        search_Form.setItemFocus("searchKey");

        $('input.dhxlist_txt_textarea').keypress(function(event){
            if(event.keyCode == 13){ //绑定回车
                findPageGrid();
            }
        });
    }
}
//刷新按钮
function doRefresh(){
    findPageGrid();
}
function doEdit(type){
    if(type!='edit')return;
    var admins =  getCheckedRowsByGrid(adminGrid, adminGrid.getColIndexById('select'));
    if (admins == null||admins.length > 1) {
        $func.alert("请选择一行再操作[编辑]", "red");
        return;
    }
    oneAdminInfo=admins[0];
    if(!oneAdminInfo||!oneAdminInfo.id){
        $func.alert("所选择行数据有问题,请选择其他行或者刷新页面重试", "red");
        return;
    }
    if(type == 'edit'){
        checkParam(admins[0].id);
    }
    openWindow(type,oneAdminInfo.id)
}

//--------------------------------------------------事件方法--------------------------------------------------------------------------
function doAdd(type){
    if(type!='add')return;
    openWindow(type)
}
function openWindow(type,id){
    if(!id) id=-1;
    if(!dhxWins)dhxWins=new dhtmlXWindows();
    dhxWins.setImagePath(basePath + "js/dhtmlx/dhtmlxWindows/codebase/imgs/");
    if(type=='add')addAdminWin=dhxWins.createWindow("addAdminWin", 10, 10, 490, 400);
    if(type=='edit')addAdminWin=dhxWins.createWindow("addAdminWin", 10, 10, 490, 400);
    addAdminWin.center();
    addAdminWin.setModal(true);
    addAdminWin.bringToTop();
    addAdminWin.setText("<span style=\"font-size:14px;\">"+(type=="add"?"新增支付宝账号":"编辑支付宝账号")+"</span>");
    addAdminWin.denyResize();
    addAdminWin.button("minmax1").hide();
    addAdminWin.button("park").hide();
    addAdminWin.attachURL(basePath+"managerAlipayUser/editAlipayUserWin?type="+type+"&id="+id);
}

function unloadPwdWin() { //放到body里面
    if (dhxWinPwd != null && dhxWinPwd.unload != null) {
        dhxWinPwd.unload();
        dhxWinPwd = w1 = pwdForm = null;
    }
}
//管理员账户状态 有效和冻结
function doFreeze(){
    var admins = getCheckedRowsByGrid(adminGrid, adminGrid.getColIndexById('select'));
    if (admins == null||admins.length > 1) {
        $func.alert("请选择一行再操作", "red");
        return;
    }
    var postData="id="+admins[0].id;
    var confirmArr = "是否冻结该支付宝账号？ <br/><font color='#ff66;'>冻结后该账户将无法登录！</font>";
    if(editStatus=="enabled"){
        postData+="&status=freeze";
    }else if(editStatus=="freeze"){
        confirmArr = "是否解除冻结该支付宝账号？ <br/><font color='#ff66;'>解除冻结后该账户恢复可登录状态！</font>";
        postData+="&status=enabled";
    }else if(editStatus=="delete"){
        $func.alert('删除状态不能更改！', 'red');
        return ;
    }
    checkParam(admins[0].id);
    $func.confirm({
        content : confirmArr,
        ok : function() {
            $.ajax({
                url: basePath+'managerAlipayUser/editAlipayUser',
                type: 'post',
                dataType: 'json',
                data:postData,
                success: function (back, textStatus, jqXHR) {
                    if(!back||!back.result){
                        $func.alert("该支付宝账号"+(editStatus=='enabled'?"冻结":editStatus=='disabled'?"解除":"恢复")+"失败！","red");
                        return;
                    }
                    $func.alert("该支付宝账号"+(editStatus=='enabled'?"冻结":editStatus=='disabled'?"解除":"恢复")+"成功！","green");
                    doRefresh();
                },
                error:function (xhr, textStatus, errorThrown) {
                    $func.alert("操作失败", "red");
                }
            });
        }
    });
}

function doDelete(){
    var admins = getCheckedRowsByGrid(adminGrid, adminGrid.getColIndexById('select'));
    if (admins == null||admins.length==0) {
        $func.alert("至少选择一行再操作[删除]", "red");
        return;
    }
    if (admins.length>1) {
        $func.alert("不支持多行删除，请选择一行再操作[删除]", "red");
        return;
    }
    checkParam(admins[0].id);
    var adminids=[];
    $.each(admins,function(k,v){
        adminids.push(v.id);
    });
    var confirmArr = "是否删除此支付宝账号？ ";
    var postData="id="+adminids;
    $func.confirm({
        content : confirmArr,
        ok : function() {
            $.ajax({
                url: basePath+ 'managerAlipayUser/delAlipayUser',
                type: 'post',
                dataType: 'json',
                data:postData,
                success: function (back) {
                    if(!back||!back.result){
                        $func.alert("删除失败！","red");
                        return;
                    }
                    $func.alert("删除成功！","green");
                    doRefresh();
                }
            });
        }
    });
}
//管理员账户状态只有两种有效和冻结
function doOnRowSelected(rowID, celInd){
    editStatus	= adminGrid.cells(rowID, adminGrid.getColIndexById('status')).getValue();
    $("#freeze").html("<span>"+(editStatus=='enabled'?"冻结账号":editStatus=='disabled'?"解冻账号":"恢复正常")+"</span>");
}
function doReset(){
    search_Form.setItemValue("searchKey","");
    //单个重置
    var tcombo=search_Form.getCombo('searchType');
    tcombo.setComboValue('');
    tcombo.readonly(true);
    var tcombo=search_Form.getCombo('status');
    tcombo.setComboValue('');
    tcombo.readonly(true);
    //批量重置
    search_Form.setFormData({
        realName:'',
        email:'',
        telephone:''
    });
}

//数据授权绑定管理功能
function doAuthority() {
    var admins = getCheckedRowsByGrid(adminGrid, adminGrid.getColIndexById('select'));
    if (admins == null||admins.length==0) {
        $func.alert("至少选择一行再操作[数据授权]", "red");
        return;
    }
    oneAdminInfo = admins[0];
    if (admins.length>1) {
        $func.alert("不支持批量授权，请选择一行再操作[数据授权]", "red");
        return;
    }
    checkParam(admins[0].id);

    if(!dhxWins)dhxWins=new dhtmlXWindows();
    dhxWins.setImagePath(basePath + "public/js/dhtmlx/dhtmlxWindows/codebase/imgs/");
    authorityWin=dhxWins.createWindow("authorityWin", 10, 10, 520, 500);
    authorityWin.center();
    authorityWin.setModal(true);
    authorityWin.bringToTop();
    authorityWin.setText("<span style=\"font-size:14px;\">"+"数据授权"+"</span>");
    authorityWin.denyResize();
    authorityWin.button("minmax1").hide();
    authorityWin.button("park").hide();
    authorityWin.attachURL(basePath+"managerAlipayUser/gotoAuthorityWin?id="+admins[0].alipay_id);
}
